package com.chezhujie.www.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.chezhujie.www.domain.Czjbusiness;
import com.chezhujie.www.domain.Czjexpress;
import com.chezhujie.www.domain.Czjorder;
import com.chezhujie.www.domain.Czjorderdetail;
import com.chezhujie.www.domain.DeviceNumber;
import com.chezhujie.www.domain.vo.BusinOrder;
import com.chezhujie.www.domain.vo.CommodityDetail;
import com.chezhujie.www.enums.Expresstatus;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.service.CzjawardstockService;
import com.chezhujie.www.service.CzjawarduseService;
import com.chezhujie.www.service.CzjbusinessService;
import com.chezhujie.www.service.CzjexpressPicService;
import com.chezhujie.www.service.CzjexpressService;
import com.chezhujie.www.service.CzjorderService;
import com.chezhujie.www.service.CzjorderdetailService;
import com.chezhujie.www.service.CzjusecouponService;
import com.chezhujie.www.service.DeviceNumberService;
import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;
import com.sys.user.domain.Xyuser;

@Controller
@RequestMapping("/businorder")
public class CzjorderAdminController extends BaseController {

	@Autowired
	private CzjorderService czjorderService;
	
	@Autowired
	private CzjbusinessService czjbusinessService;

	@Autowired
	private CzjexpressService czjexpressService;
	
	@Autowired
	private CzjawarduseService czjawarduseService;
	
	@Autowired
	private CzjawardstockService czjawardstockService;
	
	@Autowired
	private CzjusecouponService czjusecouponService;

	@Autowired
	private CzjorderdetailService czjorderdetailService;

	@Autowired
	private DeviceNumberService devicenumberService;

	@Autowired
	private CzjexpressPicService czjexpressPicService;
	

	@RequestMapping("list")
	public String list(Integer pageNo, Integer pageSize,
			HttpServletRequest req, HttpServletResponse resp, String orderCode,
			String phoneNo, Integer status, Date createTimeStart,String equipmentSerNum,
			Date createTimeEnd, HttpSession httpSession, ModelMap model) {
		setMsg(req, model);
		Map<String, Object> map = new HashMap<String, Object>();
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 20;
		}

		if (null != createTimeStart) {

			map.put("createTimeStart", createTimeStart);
			model.addAttribute("createTimeStart", createTimeStart);
		}

		if (null != equipmentSerNum) {

			map.put("equipmentSerNum", equipmentSerNum);
			model.addAttribute("createTimeStart", equipmentSerNum);
		}
		
		if (null != createTimeEnd) {

			map.put("createTimeEnd", createTimeEnd);
			model.addAttribute("createTimeEnd", createTimeEnd);
		}
		if (StringUtils.isNotBlank(orderCode)) {
			map.put("orderCode", orderCode);
			model.addAttribute("orderCode", orderCode);
		}
		if (StringUtils.isNotBlank(phoneNo)) {
			map.put("phoneNo", phoneNo);
			model.addAttribute("phoneNo", phoneNo);
		}
		if (null != status) {
			map.put("status", status);
			model.addAttribute("status", status);
		}

		try {
			Xyuser user = (Xyuser) httpSession.getAttribute("adminuser");
			if (null == user) {

				model.addAttribute("error", "用户为空");
				return "nobusin/no";
			} else {
				Czjbusiness czjbusiness = czjbusinessService
						.getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
				if (czjbusiness == null) {
					return "nobusin/nobusin";
				} else {

					map.put("businessId", czjbusiness.getId());
					// 添加已售量 、订单总金额
					Map<String, Object> soldOutMap = czjorderService
							.sumSoldOut(czjbusiness.getId());
					model.addAttribute("allSoldOut",
							soldOutMap.get("allSoldOut"));
					Map<String, Object> salesAmount = czjorderService
							.getSalesAmount(czjbusiness.getId());
					model.addAttribute("salesAmount",
							salesAmount.get("salesAmount"));

				}
				Pagination pagination = czjorderService.getOrderBybusinessid(
						pageNo, pageSize, map, model);

				List<Map<String, Object>> list = ConvertObj
						.toListMap((List<BusinOrder>) pagination.getList());
				Integer status2 = null;
				for (int i = 0; i < list.size(); i++) {
					list.get(i).put("isRefund", 0);// 默认没有退款按钮
					status2 = (Integer) list.get(i).get("status");
					if (status2 != null
							&& status2 == OrderStatus.FIN.getIndex()) {// 订单完成时间
						Date operdate = (Date) list.get(i).get("createtime");
						if ((System.currentTimeMillis() - operdate.getTime()) > 7
								* 24 * 60 * 60 * 1000) {
							list.get(i).put("isRefund", 0);
						} else {
							list.get(i).put("isRefund", 1);// 有退款按钮
						}
					}
				}
				pagination.setList(list);
				model.addAttribute("pagination", pagination);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "businorder/list";
	}

	@RequestMapping("detail")
	public String detail(@RequestParam(required = true) String id,
			@RequestParam(required = true) String businessid,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession httpSession, ModelMap model) {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("businessId", businessid);
			map.put("id", id);
			BusinOrder businOrder = czjorderService
					.getOrderBybusinessidAndOrderId(map);
			model.addAttribute("entity", businOrder);

			// 优惠券
			czjusecouponService
					.setCouponsByOrderCode(businOrder.getOrderCode(),
							businOrder.getCouponsId(), model);

			List<CommodityDetail> list = new ArrayList<CommodityDetail>();

			CommodityDetail e = null;
			for (int i = 0; i < businOrder.getBusinOrdercommodity().size(); i++) {
				e = new CommodityDetail();
				if (null != businOrder.getBusinOrdercommodity().get(i)
						&& null != businOrder.getBusinOrdercommodity().get(i)
								.getCommodityName()) {

					e.setCommodityName(businOrder.getBusinOrdercommodity()
							.get(i).getCommodityName());
				}
				/*
				 * if(null != businOrder.getBusinOrdercommodity().get(i) && null
				 * != businOrder.getBusinOrdercommodity().get(i).getSalePrice()
				 * ){
				 * 
				 * e.setSalePrice(businOrder.getBusinOrdercommodity().get(i).
				 * getSalePrice()); }
				 */

				if (null != businOrder.getOrderDetails().get(i)
						&& null != businOrder.getOrderDetails().get(i)
								.getAmount()) {

					e.setAmount(businOrder.getOrderDetails().get(i).getAmount());
					e.setSalePrice(businOrder.getOrderDetails().get(i)
							.getSalePrice());
					e.setDailyRent(businOrder.getOrderDetails().get(i)
							.getDailyRent());
					e.setPrepaidRent(businOrder.getOrderDetails().get(i)
							.getPrepaidRent());
					e.setMinPrepaidRent(businOrder.getOrderDetails().get(i)
							.getMinPrepaidRent());
					e.setLeaseDays(businOrder.getOrderDetails().get(i)
							.getLeaseDays());
					e.setLeasejisuanDays(businOrder.getOrderDetails().get(i)
							.getLeasejisuanDays());
					e.setRentDate(businOrder.getOrderDetails().get(i)
							.getRentDate());
					e.setEndRentDate(businOrder.getOrderDetails().get(i)
							.getEndRentDate());
					e.setEquipmentSerNum(businOrder.getOrderDetails().get(i)
							.getEquipmentSerNum());
					e.setEndLeaseAmount(businOrder.getOrderDetails().get(i)
							.getEndLeaseAmount());
				}

				if (null != businOrder.getBusinOrderImg()
						&& businOrder.getBusinOrderImg().size() > 0
						&& null != businOrder.getBusinOrderImg().get(i)
						&& null != businOrder.getBusinOrderImg().get(i)
								.getImagePath()) {

					e.setImagePath(businOrder.getBusinOrderImg().get(i)
							.getImagePath());
				}

				list.add(e);
			}
			model.addAttribute("list", list);
			// begin 用户结束租赁回执的照片
			Map<String, Object> params = new HashMap<>();
			params.put("expressId", businOrder.getOrderCode());
			List<Map<String, Object>> expressPics = czjexpressPicService.getListBy(params);
			model.addAttribute("expressPics", expressPics);
			// end
			//begin 快递信息
			Map<String, Object> qp = new HashMap<>();
			qp.put("orderCode", businOrder.getOrderCode());
			qp.put("status", Expresstatus.RETURN.getIndex());
			Czjexpress czjexpress= czjexpressService.getExpressByOrdercode(qp);
			model.addAttribute("czjexpress", czjexpress);
			//end
		} catch (Exception e) {
			new RuntimeException();
			e.printStackTrace();
		}

		return "businorder/detail";
	}

	/**
	 * 
	 * 方法名：getExpress 获得快递信息 创建人：RUI 时间：2017年8月21日-下午7:47:21
	 * 
	 * @param orderCode
	 * @param req
	 * @param resp
	 * @param httpSession
	 * @param model
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("getExpress")
	public String getExpress(@RequestParam(required = true) String orderCode,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession httpSession, ModelMap model) {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orderCode", orderCode);
			map.put("status", Expresstatus.DELIVER.getIndex());
			Czjexpress czjexpress = czjexpressService
					.getExpressByOrdercode(map);
			if (null == czjexpress) {
				model.addAttribute("entity", new Czjexpress());
			} else {
				model.addAttribute("entity", czjexpress);
			}
			model.addAttribute("orderCode", orderCode);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "businorder/express";
	}

	/**
	 * 
	 * 方法名：svseExpress 保存快递信息（商家） 创建人：RUI 时间：2017年8月22日-上午9:19:57
	 * 
	 * @param czjexpress
	 * @param req
	 * @param resp
	 * @param httpSession
	 * @param model
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("svseExpress")
	public String svseExpress(Czjexpress czjexpress, HttpServletRequest req,
			HttpServletResponse resp, HttpSession httpSession, ModelMap model) {

		try {
			if (null == czjexpress.getExpressId()
					|| "".equals(czjexpress.getExpressId())) {

				czjexpress.setStatus(Expresstatus.DELIVER.getIndex());
				czjexpressService.insertCzjexpress(czjexpress);
				List<Czjorder> czjorders = czjorderService
						.getOrderByOrderCode(czjexpress.getOrderCode());
				if (null != czjorders && czjorders.size() > 0) {
					Czjorder czjorder = czjorders.get(0);
					czjorder.setStatus(OrderStatus.TOSENDGOODS.getIndex());
					czjorderService.update(czjorder);// 修改状态

				}
			} else {
				czjexpressService.updateCzjexpress(czjexpress);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/businorder/list";
	}

	/**
	 * 
	 * 方法名：goDeviceNumbers 补录商品订单页面 创建人：RUI 时间：2017年8月22日-下午4:39:20
	 * 
	 * @param req
	 * @param resp
	 * @param model
	 * @param orderCode
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("goDeviceNumbers")
	public String goDeviceNumbers(HttpServletRequest req,
			HttpServletResponse resp, ModelMap model, String orderCode) {

		try {

			int amount = czjorderdetailService.getOrderAmount(orderCode);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("orderCode", orderCode);
			List<Map<String, Object>> de = devicenumberService
					.getApiList(params);
			model.addAttribute("amount", amount);
			model.addAttribute("orderCode", orderCode);
			model.addAttribute("de", de);
			if (null != de && de.size() > 0) {
				model.addAttribute("type", 1);
			} else {
				model.addAttribute("type", 2);
			}
			return "businorder/goDeviceNumbers";
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/businorder/list";
	}

	/**
	 * 
	 * 方法名：saveDeviceNumbers 补录商品号 创建人：RUI 时间：2017年8月22日-下午4:39:35
	 * 
	 * @param req
	 * @param resp
	 * @param model
	 * @param orderCode
	 * @return String
	 * @exception
	 * @since 1.0.0
	 */
	@RequestMapping("saveDeviceNumbers")
	public String saveDeviceNumbers(HttpServletRequest req,
			HttpServletResponse resp, ModelMap model, String orderCode) {

		try {

			String[] equipmentSerNum = req
					.getParameterValues("equipmentSerNums");
			String[] deviceNumberId = req.getParameterValues("deviceNumberIds");
			if(null==deviceNumberId){
						deviceNumberId=new String[equipmentSerNum.length];
			}
			DeviceNumber deviceNumber = null;
			for (int i = 0; i < equipmentSerNum.length; i++) {

					

				deviceNumber = new DeviceNumber();
				deviceNumber.setCreateTime(new Date());
				deviceNumber.setEquipmentSerNum(equipmentSerNum[i]);
				deviceNumber.setOrderCode(orderCode);
				if (deviceNumberId[i] != null) {
					deviceNumber.setDeviceNumberId(deviceNumberId[i]);
					devicenumberService.update(deviceNumber);
				} else {

					deviceNumber.setDeviceNumberId(UUIDUtils.getUUID());
					devicenumberService.insert(deviceNumber);

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/businorder/list";
	}
	
	
	/**
	 * 
	 * 方法名：beginBilling 开始计费
	 * 创建人：RUI
	 * 时间：2017年8月23日-下午4:24:45 
	 * @param req
	 * @param resp
	 * @param model
	 * @param orderCode void
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("beginBilling")
	public void beginBilling(HttpServletRequest req,
			HttpServletResponse resp, ModelMap model, String orderCode,String orderid) {

		try {
 
			if(StringUtils.isBlank(orderCode)){
				
				jsonResult(0, "187", "订单编号为空", "", resp);
				return ;
			}
			Czjorderdetail czjorderdetail=czjorderdetailService.queryByCode(orderCode);
			if(null == czjorderdetail){
				jsonResult(0, "188", "没有此订单", "", resp);
				return ;
			}
			czjorderdetail.setRentDate(new Date());
			czjorderdetailService.update(czjorderdetail);
			
			Czjorder czjorder=new Czjorder();
				czjorder.setId(orderid);
				czjorder.setStatus(OrderStatus.INLEASE.getIndex());
			czjorderService.update(czjorder);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "189", "系统错误", "", resp);
		}
		jsonResult(1, "", "", "", resp);
		
	}
	
	/**
	 * 
	 * 方法名：confirmReturn 确认归还
	 * 创建人：RUI
	 * 时间：2017年8月23日-上午10:46:41 
	 * @param req
	 * @param resp
	 * @param model
	 * @param id void
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("confirmReturn")
	public void confirmReturn(HttpServletRequest req,
			HttpServletResponse resp, ModelMap model, String id) {

		try {
 
			if(StringUtils.isBlank(id)){
				
				jsonResult(0, "187", "订单编号为空", "", resp);
				return ;
			}
			Czjorder czjorder=new Czjorder();
				czjorder.setId(id);
				czjorder.setStatus(OrderStatus.RETURNED.getIndex());
			czjorderService.update(czjorder);
		

		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "189", "系统错误", "", resp);
		}
		jsonResult(1, "", "", "", resp);
		
	}
	
	/***
	 * 
	 * 方法名：beginOrder 订单开始处理
	 * 创建人：RUI
	 * 时间：2017年8月23日-下午4:24:19 
	 * @param req
	 * @param resp
	 * @param model
	 * @param id void
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("beginOrder")
	public void beginOrder(HttpServletRequest req,
			HttpServletResponse resp, ModelMap model, String id) {

		try {
 
			if(StringUtils.isBlank(id)){
				
				jsonResult(0, "187", "订单编号为空", "", resp);
				return ;
			}
			Czjorder czjorder=new Czjorder();
				czjorder.setId(id);
				czjorder.setStatus(OrderStatus.SENDGOODSING.getIndex());
			czjorderService.update(czjorder);
		

		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "189", "系统错误", "", resp);
		}
		jsonResult(1, "", "", "", resp);
		
	}
	
	/***
	 * 
	 * 方法名：beginOrder 购买的确认收货
	 * 创建人：RUI
	 * 时间：2017年8月23日-下午4:24:19 
	 * @param req
	 * @param resp
	 * @param model
	 * @param id void
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping("confirmReceipt")
	public void confirmReceipt(HttpServletRequest req,
			HttpServletResponse resp, ModelMap model, String id) {

		try {
 
			if(StringUtils.isBlank(id)){
				
				jsonResult(0, "187", "订单编号为空", "", resp);
				return ;
			}
			Czjorder czjorder=new Czjorder();
				czjorder.setId(id);
				czjorder.setStatus(OrderStatus.FIN.getIndex());
			czjorderService.update(czjorder);
		

		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "189", "系统错误", "", resp);
		}
		jsonResult(1, "", "", "", resp);
		
	}

	
	

	private void setMsg(HttpServletRequest req, ModelMap model) {
		model.addAttribute("failed", req.getParameter("failed"));
		model.addAttribute("success", req.getParameter("success"));
	}
}
